<script setup>
import { ref, reactive, toRaw, nextTick } from 'vue';
import { service, cache } from '@utils';
import { ElMessage } from 'element-plus';
import { forEach } from 'lodash';

const emit = defineEmits(['refresh']);

const props = defineProps({
    permissionTypes: Array,
    menus: Array,
});

const visible = ref(false);
const formRef = ref();
const menuRef = ref();
const defaultExp = ref();
const disabled = ref(false);
const title = ref('');
// 1:全部数据权限、2:自定义数据权限、3:本部门数据权限、4：本部门及以下数据权限/
const state = reactive({
    param: {},
    searchData: [],
    dataType: [
        {
            value: 1,
            label: '全部数据',
        },
        {
            value: 2,
            label: '自定义数据',
        },
        {
            value: 3,
            label: '本部门数据',
        },
        {
            value: 4,
            label: '本部门及以下数据(本人数据)',
        },
    ],
});

const rules = {
    name: [{ required: true, message: '请输入', trigger: 'blur' }],
    code: [{ required: true, message: '请输入', trigger: 'blur' }],
    dataScope: [{ required: true, message: '请输入', trigger: 'blur' }],
};

const open = (type, item, treeData) => {
    title.value = type;
    state.param = JSON.parse(JSON.stringify(item));
    state.treeData = treeData;
    visible.value = true;
    let menuData = state.param.menuIds;
    nextTick(() => {
        if (type == '授权菜单') {
            menuData.forEach(item => {
                menuRef.value.setChecked(item, true, false);
            });
        }
    });

    if (props.menus) {
        let array = [];
        props.menus.forEach(item => {
            array.push(item.id);
            if (item.children) {
                item.children.forEach(item1 => {
                    array.push(item1.id);
                });
            }
        });
        defaultExp.value = array;
    }
};

const close = () => {
    visible.value = false;
    state.param = {};
    defaultExp.value = null;
    disabled.value = false;
};

const sure = async () => {
    formRef.value.validate(valid => {
        if (valid) {
            realSubmit();
        }
    });
};
const realSubmit = async () => {
    let res;
    if (title.value == '新增') {
        res = await service.auth.roleSave(toRaw(state.param));
    } else if (title.value == '编辑') {
        res = await service.auth.roleUpdate(toRaw(state.param));
    } else if (title.value == '授权数据') {
        let param = JSON.parse(JSON.stringify(state.param));
        let data = {
            id: param.id,
            dataScope: param.dataScope,
            orgIds: param.orgIds ? param.orgIds.join(',') : '',
        };
        if (data.dataScope != 2) {
            delete data.orgIds;
        }
        res = await service.auth.roleData(toRaw(data));
    } else {
        let param = JSON.parse(JSON.stringify(state.param));
        let menuCheckData = menuRef.value.getCheckedNodes(false, true);
        let menuIds = [];
        menuCheckData.forEach(item => {
            menuIds.push(item.id);
        });
        let data = {
            id: param.id,
            menuIds: menuIds ? menuIds.join(',') : '',
        };
        res = await service.auth.roleMenu(toRaw(data));
    }
    if (res.resultCode == 8200) {
        ElMessage.success(title.value + '成功');
        close();
        emit('refresh', !!state.param.id);
    }
};

// const menuClick = (node, check) => {
// if (state.param.menuId.indexOf(node.id) === -1) {
//     //没有-设置选中
//     //判断有无子节点
//     if (node.children && node.children.length > 0) {
//         setChildrenCheck(node.children, true);
//     }
//     //判断父节点是否选中
//     if (node.parentId != null && node.parentId != 0) {
//         setParentCheck(node);
//     }
// } else {
//     //取消选中
//     if (node.children && node.children.length > 0) {
//         setChildrenCheck(node.children, false);
//     }
// }
// state.param.menuIds = check.checkedKeys;
// };

// const setChildrenCheck = (list, isChecked) => {
//     for (let x = 0; x < list.length; x++) {
//         menuRef.value.setChecked(list[x].id, isChecked, false);
//         if (list[x].children != undefined && list[x].children.length > 0) {
//             setChildrenCheck(list[x].children, isChecked);
//         }
//     }
// };

// const setParentCheck = node => {
//     if (state.param.menuId.indexOf(node.parentId) == -1) {
//         state.param.menuId.push(node.parentId);
//         menuRef.value.setChecked(node.parentId, true, false);
//         const n = menuRef.value.getNode(node.parentId);
//         if (n && n.data) setParentCheck(n.data);
//     }
// };
//把方法暴露给父组件
defineExpose({
    open,
});
</script>

<template>
    <el-dialog v-model="visible" :title="title" center :close-on-click-modal="false" @close="close" destroy-on-close top="10vh">
        <section>
            <el-form :model="state.param" :rules="rules" ref="formRef" label-width="100px" label-suffix=":" onsubmit="return false;">
                <div v-if="title == '新增' || title == '编辑'">
                    <el-form-item label="角色名" prop="name">
                        <el-input v-model="state.param.name" placeholder="请输入参数名" clearable :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="唯一编码" prop="code">
                        <el-input v-model="state.param.code" placeholder="请输入参数名" clearable :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="state.param.sort" type="number" placeholder="请输入参数名" clearable :disabled="disabled"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="state.param.remark" type="textarea" placeholder="请输入描述" clearable :disabled="disabled"></el-input>
                    </el-form-item>
                </div>
                <div v-else-if="title == '授权数据'">
                    <el-form-item label="数据权限" prop="dataScope">
                        <el-select v-model="state.param.dataScope" style="width: 100%" placeholder="请选择数据权限" clearable :disabled="disabled">
                            <el-option v-for="item in state.dataType" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择机构" prop="dataScope" v-if="state.param.dataScope == 2">
                        <el-tree-select style="width: 100%" v-model="state.param.orgIds" :data="state.treeData" multiple show-checkbox :check-strictly="true" :default-checked-keys="state.param.orgIds" :default-expanded-keys="state.param.orgIds" filterable :props="{ label: 'name', value: 'id' }" node-key="id" />
                    </el-form-item>
                </div>
                <div v-else>
                    <el-form-item label="菜单" prop="menuId">
                        <!-- :default-checked-keys="state.param.menuIds" -->
                        <el-tree ref="menuRef" :getCheckedNodes="true" class="tree-border" :data="menus" show-checkbox node-key="id" :disabled="disabled" :check-strictly="false" :default-expanded-keys="state.param.menuIds" style="width: 100%;height:65vh;overflow: auto;" :props="{ label: 'name', value: 'id', disabled: disabled ? 'id' : '' }"></el-tree>
                    </el-form-item>
                </div>
            </el-form>
        </section>

        <template #footer v-if="!disabled">
            <span class="flex-align-end">
                <div class="margin-right20">
                    <el-button @click="close">取消</el-button>
                </div>
                <el-button type="primary" @click="sure">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
